package time.after.time.sys.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

import time.after.time.service.ServiceException;

public class HttpJsonClient {
	private static final Logger logger = LoggerFactory.getLogger(HttpJsonClient.class);
	private static ObjectMapper mapper = new ObjectMapper();
	
	public static String getJsonData(String url, Map<String, Object> params) throws ServiceException{
		try{
			return getJsonData(url,params,false);
		}catch(Exception e){
			logger.error(url, e);
			throw new ServiceException("get data from ["+url+"] error",e);
		}
	}
	private static String getJsonData(String url, Map<String, Object> params,boolean except) throws ClientProtocolException,
			IOException {
		  HttpClient httpclient = new DefaultHttpClient();
		  HttpParams httpParams= httpclient.getParams(); 
		  HttpConnectionParams.setConnectionTimeout(httpParams,15000);//连接超时时间15秒
		  HttpConnectionParams.setSoTimeout(httpParams, 15000);// 获取数据超时时间
		try {
			logger.debug("begin to get url:" + url);
			if (params != null && !(params.isEmpty())) {
				List<NameValuePair> values = new ArrayList<NameValuePair>();
				for (Map.Entry<String, Object> entity : params.entrySet()) {
					BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString());
					values.add(pare);
					
				}
				String str = URLEncodedUtils.format(values, "UTF-8");
				if (url.indexOf("?") > -1) {
					url += "&" + str;
				} else {
					url += "?" + str;
				}
			}
			logger.debug("after url:"+url);
			HttpGet httpget = new HttpGet(url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			return httpclient.execute(httpget, responseHandler);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	public static String deleteIndexData(String url) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		try {
			logger.debug("begin to get url:" + url);
			HttpDelete httpget = new HttpDelete(url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			return httpclient.execute(httpget, responseHandler);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	public static String postJsonDataByJson(String url, Map<String, ?> params) throws ClientProtocolException,
			IOException {
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);

			if (params != null) {
				String str = mapper.writeValueAsString(params);
				ByteArrayEntity mult = new ByteArrayEntity(str.getBytes("UTF-8"));
				httpPost.setEntity(mult);
			}

			logger.debug("begin to post url:" + url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			return httpclient.execute(httpPost, responseHandler);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

	}

	public static String postJsonData(String url, Map<String, ?> params,boolean except) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);

			if (params != null) {
				List<NameValuePair> values = new ArrayList<NameValuePair>();
				for (Map.Entry<String, ?> entity : params.entrySet()) {
					BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString());
					values.add(pare);

				}

				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, "UTF-8");
				httpPost.setEntity(entity);
			}

			logger.debug("begin to post url:" + url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			return httpclient.execute(httpPost, responseHandler);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}
	
	public static String postJsonData(String url, Map<String, ?> params) throws ServiceException {
		   
		 try {
			return postJsonData(url,params,false);
		} catch (Exception e) {
			logger.error(url, e);
			throw new ServiceException("get data from ["+url+"] error",e);
		}
	}
	

	public static <T> T postJsonObjectData(String url, HashMap<String, Object> params, Class<T> cls)
			throws ClientProtocolException, IOException {
		String str = postJsonData(url, params,false);
		return mapper.readValue(str, cls);
	}
	
	public static void main(String[] args) {
		String url="http://sso.ztgame.com/passport/soap/soapserver_passport.php/ValidateAdOnlyByPasswd";
		Map<String,Object> map=Maps.newHashMap();
		map.put("user_name", "huming");
		map.put("passwd", "aliyador#11");
		String back=getJsonData(url, map);
		System.out.println(back);
	}
}
